<div class="col-sm-10">

    <div class="page-header" style="margin-top: 10px;
    margin-bottom: 5px;
    background-color: #fff;
    border-radius: 4px;
    border: 1px solid #ddd;
    padding: 15px;">
        <h2 style="margin: 0px">部门职能 / 部门管理</h2>
    </div>

    <!--部门处理框-->
    <div class="panel panel-default">
        <div class="panel-body">
            <!--搜索栏-->
<!--            <div class="navbar-collapse" id="bs-example-navbar-collapse-1">-->
<!--                <form class="navbar-form navbar-left" role="search">-->
<!--                    <div class="form-group">部门名称：-->
<!--                        <input type="text" class="form-control" placeholder="Search">-->
<!--                    </div>-->
<!--                    <button type="submit" class="btn btn-default">查询</button>-->
<!--                </form>-->
<!--            </div>-->

            <!--搜索栏-->
            <div class="navbar-collapse" id="bs-example-navbar-collapse-1">
                <nav class="navbar navbar-default">
                    <div class="container-fluid">
                        <div class="navbar-header" style="width: 98%;">
                            <form class="navbar-form navbar-left" style="width: 98%;">
                                <div class="form-group">
                                    部门名称：
                                    <input id="search_input" type="text" class="form-control" placeholder="Search">
                                    <button class="btn btn-default" type="button" id="search_btn">搜索</button>
                                </div>
                                <div class="form-group" style="float: right;">
                                    <!--添加按钮-->
                                    <button class="btn btn-success" type="button" id="saveBtn">添加部门</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </nav>
            </div>

            <div class="navbar-collapse" id="bs-example-navbar-collapse-2">

                <!--表格-->
<!--                用于显示部门信息的表格-->
                <table id="department_curd_table" class="table table-hover table-bordered table-striped">
                    <caption></caption>
                    <thead>
                    <tr>
                        <th>
                            <input type="checkbox" id="department_check_all">
                        </th>
                        <th>id</th>
                        <th>部门名称</th>
                        <th>部门经理</th>
                        <th>简介</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody>

                    </tbody>
                </table>

            </div>
            <!--分页栏-->
            <nav aria-label="Page navigation">
                <ul id="page_nav" class="pager">

                </ul>
            </nav>
        </div>
    </div>
</div>
<!--修改部门对话框-->
<div class="modal fade" id="updateDepartmentModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title">编辑部门信息</h4>
            </div>
            <div class="modal-body">

                <form id="update_department_form" class="form-horizontal">
                    <div class="form-group" style="display:none">
                        <label class="col-sm-2 control-label">ID</label>
                        <div class="col-sm-10">
                            <input type="text" name="id" class="form-control" id="id_update_input" disabled>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">部门名</label>
                        <div class="col-sm-10">
                            <!-- placeholder是显示输入提示的属性 -->
                            <!-- name属性的值与实体类的属性名相同是为了能自动进行类对象的实例化 -->
                            <input type="text" name="department_name" class="form-control"
                                   id="department_name_update_input"
                                   placeholder="部门名">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">部门经理</label>
                        <div class="col-sm-10">
                            <input type="text" name="manager" class="form-control"
                                   id="manager_update_input"
                                   placeholder="经理名称">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">部门简介</label>
                        <div class="col-sm-10">
                            <input type="text" name="brief" class="form-control" id="nick_update_input"
                                   placeholder="简介信息">
                            <span class="help-block"></span>
                        </div>
                    </div>
                </form>

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" id="update_department_btn" class="btn btn-primary">修改</button>
            </div>
        </div>
    </div>
</div>


<!-- 该模态框用于删除角色 -->
<div class="modal fade" id="deleteDepartmentModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <!-- 模态框标题 -->
                <h4 class="modal-title">删除部门</h4>
            </div>
            <div class="modal-body">
                <p id="delete_tip_p">模态框内容</p>
                <p id="delete_id_p" style="visibility: hidden"></p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" id="delete_department_btn" class="btn btn-danger">确认</button>
            </div>
        </div>
    </div>
</div>


<!--添加部门对话框-->
<div class="modal fade" id="saveDepartmentModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">x</span>
                </button>
                <h4 class="modal-title">添加部门信息</h4>
            </div>
            <div class="modal-body">

                <form id="add_department_form" class="form-horizontal">
                    <div class="form-group" style="display:none">
                        <label class="col-sm-2 control-label">ID</label>
                        <div class="col-sm-10">
                            <input type="text" name="id" class="form-control" id="id_add_input" disabled>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">部门名称</label>
                        <div class="col-sm-10">
                            <!-- placeholder是显示输入提示的属性 -->
                            <!-- name属性的值与实体类的属性名相同是为了能自动进行类对象的实例化 -->
                            <input type="text" name="department_name" class="form-control"
                                   id="department_name_add_input"
                                   placeholder="部门名">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">部门经理</label>
                        <div class="col-sm-10">
                            <input type="text" name="manager" class="form-control" id="manager_add_input"
                                   placeholder="经理名称">
                            <span class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">部门简介</label>
                        <div class="col-sm-10">
                            <input type="text" name="brief" class="form-control" id="nick_add_input"
                                   placeholder="简介名称">
                            <span class="help-block"></span>
                        </div>
                    </div>
                </form>
            </div>

            <div class="modal-footer">
                <button type="button" id="department_add_cancel" class="btn btn-default" data-dismiss="modal">关闭
                </button>
                <button type="button" id="department_add_confirm" class="btn btn-primary">确认</button>
            </div>
        </div>
    </div>
</div>

<script type="text/javascript">
    //加载页面后进行的操作
    $(function () {
        //发送跳转请求到用户表第1页
        to_page(1);
        //绑定按钮点击事件
        bindOnEvent();
    });

    //该方法用于跳转到页面并查询
    function to_page(pn) {
        //将当前页数存入sessionStorage
        sessionStorage.setItem("pageNum", pn);
        $.ajax({
            url: departmentInterface,//非Rest
            data: "pn=" + pn,
            type: "GET",
            beforeSend: function(XMLHttpRequest ) {
                //在请求头部设置accessToken
                XMLHttpRequest.setRequestHeader("accessToken", sessionStorage.getItem("accessToken"));
            },
            //请求成功后的回调函数
            //result是请求成功后返回的Json结果
            success: function (result) {
                // 构建部门表
                build_department_table(result);
                // 构建构建页数信息条
                build_page_info(result);
                // 构建分页导航条
                build_department_nav(result);
            }
        });
    }

    //该方法用于构建部门数据表
    function build_department_table(result) {
        let $departmentTable = $("#department_curd_table tbody");
        $departmentTable.empty();//添加前需要先清空

        let departmentList = result.dataMap.pageInfo.list;//部门的信息表
        let tableSize = result.dataMap.pageInfo.pageSize;//数据表每行的数量
        let createNums = 0;//当前已创建数据行的数量

        //Jquery里的$.each()遍历中，index代表当前遍历的索引，item代表当前遍历的数据
        $.each(departmentList, function (index, item) {
            // showMsg = showMsg + index+":"+ item.id+":"+item.department_name+"\n";
            let $checkbox = $("<input type='checkbox' class='department_check_item'/>");//创建选框
            let $checkboxTd = $("<td></td>").append($checkbox);//创建选框格并加入选框
            let $departmentIdTd = $("<td></td>").append(item.id);//创建id格并加入id数据
            let $department_nameTd = $("<td></td>").append(item.department_name);//创建部门名格并加入部门名数据
            let $managerTd = $("<td></td>").append(item.manager);
            let $briefTd = $("<td></td>").append(item.brief);//创建部门经理格并加入职位数据
            let $updateBtn = $("<button class=\"btn btn-primary btn-sm  update_department_btn\" style='margin-right:10px;margin-top:3px;'>修改</button>");
            let $deleteBtn = $("<button class=\"btn btn-danger btn-sm  delete_department_btn\" style='margin-right:10px;margin-top:3px;'>删除</button>");
            let $operationTd = $("<td></td>").append($updateBtn).append($deleteBtn);//创建操作格并加入操作按钮

            let $departmentTr = $("<tr></tr>")//创建用户数据行并加入各种数据格子
                .append($checkboxTd)
                .append($departmentIdTd)
                .append($department_nameTd)
                .append($managerTd)
                .append($briefTd)
                .append($operationTd);

            $departmentTable.append($departmentTr);//将数据行加入表格中
            createNums++;//已创建数据行的数量加1
        });

        //构造空数据行
        for (let i = createNums; i < tableSize; i++) {
            let $departmentTr = $("<tr></tr>");//创建用户数据行并加入各种数据格子
            for (let j = 0; j < 6; j++) {
                let $departmentTd = $("<td>&nbsp;</td>");//创建选框
                $departmentTr.append($departmentTd);//加入选框
            }
            $departmentTable.append($departmentTr);//将数据行加入表格中
        }
    }

    //该方法用于构建页数信息条
    function build_page_info(result) {
        let $pageInfo = $("#page_info");
        $pageInfo.empty();//先清空"页数信息条"里的信息

        let pageNum = result.dataMap.pageInfo.pageNum;//当前页码
        let pageSize = result.dataMap.pageInfo.pageSize;//页容量
        let pages = result.dataMap.pageInfo.pages;//总页数
        let total = result.dataMap.pageInfo.total;//总数据量

        sessionStorage.setItem("nowPage",pageNum);
        sessionStorage.setItem("totalRecords",total);

        let $pageInfoP = $("<span></span>").append(
            "当前页:" + pageNum + "&nbsp;&nbsp;" +
            "页显示量:" + pageSize + "&nbsp;&nbsp;" +
            "总页数:" + pages + "&nbsp;&nbsp;" +
            "总数据量:" + total);

        $pageInfo.append($pageInfoP);//再往"页数信息条"里添加信息
    }

    //该方法用于构建分页导航条
    function build_department_nav(result) {
        let $navUl = $("#page_nav");//找到需要被添加的导航栏对象
        $navUl.empty();//添加前需要先清空

        let pageNum = result.dataMap.pageInfo.pageNum;//当前页码
        let pageSize = result.dataMap.pageInfo.pageSize;//页容量
        let pages = result.dataMap.pageInfo.pages;//总页数
        let total = result.dataMap.pageInfo.total;//总数据量
        let isFirstPage = result.dataMap.pageInfo.isFirstPage;//是否是首页的标识
        let isLastPage = result.dataMap.pageInfo.isLastPage;//是否是尾页的标识
        let navigatepageNums = result.dataMap.pageInfo.navigatepageNums;//导航栏要显示的数字们

        let $firstPageLi = $("<li></li>").append(
            $("<a></a>").append("首页").attr("href", "#")
        );
        let $prePageLi =
            $("<li></li>").append(
                $("<a></a>").append(
                    $("<span></span>").append("&laquo;")
                ).attr("href", "#")
            );

        let $nextPageLi =
            $("<li></li>").append(
                $("<a></a>").append(
                    $("<span></span>").append("&raquo;")
                ).attr("href", "#")
            );
        let $lastPageLi = $("<li></li>").append(
            $("<a></a>").append("尾页").attr("href", "#")
        );

        //如果是首页，则有两个按钮不能点击
        if (isFirstPage) {
            $firstPageLi.addClass("disabled");//第一页li添加disabled的class
            $firstPageLi.find("a").removeAttr("href");//找到第一页li下的a标签并清除属性

            $prePageLi.addClass("disabled");//前一页li添加disabled的class
            $prePageLi.find("a").removeAttr("href");//找到前一页li下的a标签并清除href属性
        } else {
            $firstPageLi.click(function () {
                to_page(1);
            });
            $prePageLi.click(function () {
                to_page(pageNum - 1);
            });
        }

        //如果是尾页，则有两个按钮不能点击
        if (isLastPage) {
            $lastPageLi.addClass("disabled");//最后页li添加disabled的class
            $lastPageLi.find("a").removeAttr("href");//找到最后页li下的a标签并清除属性

            $nextPageLi.addClass("disabled");//后一页li添加disabled的class
            $nextPageLi.find("a").removeAttr("href");//找到后一页li下的a标签并清除href属性
        } else {
            $lastPageLi.click(function () {
                to_page(pages);
            });
            $nextPageLi.click(function () {
                to_page(pageNum + 1);
            });
        }

        //添加"首页"按钮
        $navUl.append($firstPageLi);
        //添加"上一页"按钮
        $navUl.append($prePageLi);
        //遍历添加所有要显示的页码
        $.each(navigatepageNums, function (index, item) {
            let $numLi = $("<li></li>").append(
                $("<a></a>").append(item).attr("href", "#")
            );
            //如果目前的页码真的与遍历页码相等
            if (pageNum == item) {
                $numLi.addClass("active");
                $numLi.empty();//清除里面能点击的a标签
                $numLi.append(
                    $("<span></span>").append(item).append(
                        $("<span></span>").addClass("sr-only")
                    )
                );
            }
            //设置显示的页码格子的点击事件
            $numLi.click(function () {
                to_page(item);
            });

            $navUl.append($numLi);//将每一个要显示的页码加入导航栏中
        });
        //添加"下一页"按钮
        $navUl.append($nextPageLi);
        //添加"尾页"按钮
        $navUl.append($lastPageLi);
        //给该分页条修改magin
        $navUl.css({
            margin: 5
        });
    }

    // /**
    //  * 该方法用于清除错误提示
    //  */
    // function clearDepartmentForm() {
    //     let $department_name_add_input = $("#department_name_add_input");
    //     let $manager_add_input = $("#manager_add_input");
    //     let $nick_add_input = $("#nick_add_input");
    //
    //     //移除所有的错误提示样式
    //     $department_name_add_input.parent().removeClass();
    //     $department_name_add_input.next("span").empty();
    //     $manager_add_input.parent().removeClass("has-error");
    //     $manager_add_input.next("span").empty();
    //     $nick_add_input.parent().removeClass("has-error");
    //     $nick_add_input.next("span").empty();
    // }


    function showErrorToFrom(result) {
        //先清除错误提示
        // clearDepartmentForm();

        let $department_name_add_input = $("#department_name_add_input");
        let $manager_add_input = $("#manager_add_input");
        let $nick_add_input = $("#nick_add_input");

        if (result.dataMap.fieldErrors.department_name != undefined) {//若不匹配，显示提示
            $department_name_add_input.parent().addClass(errInputClass);
            $department_name_add_input.next("span").append(result.dataMap.fieldErrors.department_name);
        }
        if (result.dataMap.fieldErrors.manager != undefined) {//若不匹配，显示提示
            $manager_add_input.parent().addClass("has-error");
            $manager_add_input.next("span").append(result.dataMap.fieldErrors.manager);
        }
        if (result.dataMap.fieldErrors.nick != undefined) {//若不匹配，显示提示
            $nick_add_input.parent().addClass("has-error");
            $nick_add_input.next("span").append(result.dataMap.fieldErrors.nick);
        }
    }

    /**
     * 该方法用于给控件绑定事件
     */
    function bindOnEvent() {

        //test1Btn
        $('#test1Btn').click(function () {
            alertUtil.message("测试消息", "warning");
        });
        //添加部门绑定弹出模态框的点击事件
        $('#saveBtn').click(function () {
            //调用html元素的清除表单数据方法
            $("#add_department_form")[0].reset();
            //清除错误提示
            // clearDepartmentForm();
            //弹出模态框
            $('#saveDepartmentModal').modal({
                backdrop: 'static'
            });

        });

        //绑定弹出更新模态框的事件
        $(document).on("click", ".update_department_btn", function () {
            let departmentID = $(this).parents("tr").find("td:eq(1)").text();
            let department_name = $(this).parents("tr").find("td:eq(2)").text();
            let manager = $(this).parents("tr").find("td:eq(3)").text();
            let nick = $(this).parents("tr").find("td:eq(4)").text();
            $("#id_update_input").val(departmentID);//需更新的id
            $("#department_name_update_input").val(department_name);//需更新的部门名
            $("#manager_update_input").val(manager);//需要更新的职位
            $("#nick_update_input").val(nick);//需更新的密码
            console.log("更新前：department_name："+department_name);
            console.log("更新前：nick："+nick);

            $("#updateDepartmentModal").modal({//弹出模态框
                backdrop: "static"
            });
        });


        //确认更新按钮的点击事件
        $("#update_department_btn").click(function () {
            let departmentID = $("#id_update_input").val();
            let department_name = $("#department_name_update_input").val();
            let manager = $("#manager_update_input").val();
            let brief = $("#nick_update_input").val();

            let departmentData = {
                id: departmentID,
                department_name: department_name,
                manager: manager,
                brief: brief,
            };
            let departmentJsonData = JSON.stringify(departmentData);
            console.log("更新时：departmentData:" + departmentData);
            console.log("更新时：departmentJsonData:" + departmentJsonData);

            $.ajax({//请求修改用户信息
                url: departmentInterface,
                data: departmentJsonData,
                contentType: 'application/json;charset=utf-8',
                type: "PUT",
                beforeSend: function(XMLHttpRequest ) {
                    //在请求头部设置accessToken
                    XMLHttpRequest.setRequestHeader("accessToken", sessionStorage.getItem("accessToken"));
                },
                //请求成功后的回调函数
                //result是请求成功后返回的Json结果
                success: function (result) {
                    if (result.code == 200) {
                        alertUtil.message(result.msg);
                    } else {
                        alertUtil.message(result.msg, "danger");
                    }
                    //关闭模态框
                    $('#updateDepartmentModal').modal('hide');
                    //跳转到尾页
                    to_page(sessionStorage.getItem("totalRecords"));
                },
                error: function () {
                    $('#updateDepartmentModal').modal('hide');
                    alertUtil.message("服务器后端未响应!", "danger");
                }
            });
        });

        // $('#updateBtn').click(function () {
        //     $('#updateUserModal').modal({
        //         show: true,
        //         backdrop: 'static'
        //     });
        // });

        //绑定弹出模态框的点击事件
        $("#add_department_btn").click(function () {
            //调用html元素的清除表单数据方法
            $("#add_department_form")[0].reset();
            //清除错误提示
            clearDepartmentForm();
            //弹出模态框
            $("#addDepartmentModal").modal({
                backdrop: "static"
            });
        })

        //删除用户绑定弹出模态框的点击事件
        $(document).on("click", ".delete_department_btn", function () {
            let departmentID = $(this).parents("tr").find("td:eq(1)").text();
            let department_name = $(this).parents("tr").find("td:eq(2)").text();
            $("#delete_id_p").empty();
            $("#delete_id_p").text(departmentID);
            $("#delete_tip_p").empty();
            $("#delete_tip_p").append("确认删除部门<strong>[" + department_name + "]</strong>吗？<strong>注意，此操作不可逆！</strong>");//添加删除的提示

            $('#deleteDepartmentModal').modal({
                backdrop: 'static'
            });
        });

        //确认删除按钮的点击事件
        $("#delete_department_btn").click(function () {
            let departmentID = $("#delete_id_p").text();//找到要删除的id
            $.ajax({//请求删除该用户
                url: departmentInterface + "?idList=" + departmentID,
                // data: "idList=" + departmentID,
                type: "DELETE",
                beforeSend: function(XMLHttpRequest ) {
                    //在请求头部设置accessToken
                    XMLHttpRequest.setRequestHeader("accessToken", sessionStorage.getItem("accessToken"));
                },
                //请求成功后的回调函数
                //result是请求成功后返回的Json结果
                success: function (result) {
                    if (result.code == 200) {
                        alertUtil.message(result.msg, "success");
                    } else {
                        alertUtil.message(result.msg, "danger");
                    }
                    $("#deleteDepartmentModal").modal('hide');//关闭删除模态框
                    to_page(sessionStorage.getItem("nowPage"));//跳转到当前页(刷新)
                },
                error: function () {
                    $("#deleteDepartmentModal").modal('hide');//关闭删除模态框
                    alertUtil.message("服务器后端未响应!", "danger");
                }
            });
        });

        //给各输入框添加焦点模糊事件
        let $department_name_add_input = $("#department_name_add_input");
        let $manager_add_input = $("#manager_add_input");
        let $nick_add_input = $("#nick_add_input");
        $department_name_add_input.bind("input propertychange", function () {
            checkDepartmentForm();
        });
        $manager_add_input.bind("input propertychange", function () {
            checkDepartmentForm();
        });
        $nick_add_input.bind("input propertychange", function () {
            checkDepartmentForm();
        });


        //绑定测试的按钮的点击事件
        $("#test1_btn").click(function () {
            alertUtil.message("我是弹出框的显示的结果"); // 直接调用commonUtil对象的message方法
        });

        //确认添加部门的按钮的点击事件
        $("#department_add_confirm").click(function () {
            //使用jq自带的序列化方法直接将表格中的数据取出
            let departmentData = $("#add_department_form").serialize();
            // alert(departmentData);

            $.ajax({
                url: departmentInterface,
                data: departmentData,
                type: "POST",
                beforeSend: function(XMLHttpRequest ) {
                    //在请求头部设置accessToken
                    XMLHttpRequest.setRequestHeader("accessToken", sessionStorage.getItem("accessToken"));
                },
                //请求成功后的回调函数
                //result是请求成功后返回的Json结果
                success: function (result) {
                    //判断保存的状态，200为成功，400为失败
                    if (result.code == 200) {
                        //提示保存成功
                        alertUtil.message(result.msg, "success");
                        //来到最后一页
                        to_page(sessionStorage.getItem("totalRecords"));
                    } else {
                        console.log(result);
                        // 查看是否有后端回传的详细错误提示
                        if (result.dataMap.fieldErrors != undefined) {
                            //将失败的提示显示到模态框上
                            showErrorToFrom(result);
                        } else {
                            //提示保存失败
                            alertUtil.message(result.msg, "danger");
                        }
                    }
                    //关闭模态框
                    $("#saveDepartmentModal").modal("hide");
                }
            });

        });

        //绑定全选框的点击事件
        $("#department_check_all").click(function () {
            //用.prop()函数来获取或修改dom原生的属性
            let nowCheckAll = $(this).prop("checked");
            $(".department_check_item").prop("checked", nowCheckAll);
        });

        //绑定单行数据选框的点击事件 ( on(事件,选择器,方法) 方法附加的事件处理程序适用于匹配选择器的当前及未来的元素)
        $(document).on("click", ".department_check_item", function () {
            //选中的数量和全部可选中的数量是否相等的标识
            let isCheckAll = $(".department_check_item:checked").length == $(".department_check_item").length;
            $("#department_check_all").prop("checked", isCheckAll);
        });
    }
</script>